package conversationGroup

import (
	"common/comCopier"
	"common/comMysql"
	"common/dao/model"
	"context"
	"gorm.io/gorm"

	"gateway/internal/svc"
	"gateway/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type ConversationGroupListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewConversationGroupListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ConversationGroupListLogic {
	return &ConversationGroupListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ConversationGroupListLogic) ConversationGroupList(req *types.ConversationGroupListRequest) (*types.ConversationGroupListRespList, error) {
	var (
		params = comMysql.QueryList{}
		resp   = types.ConversationGroupListRespList{}
		user   = model.User{}
	)
	tokenInfo := l.ctx.Value("token")
	err := comCopier.CopyWithOption(&user, tokenInfo)
	if err != nil {
		return nil, err
	}
	params.Page = req.Page
	params.Size = req.PageSize
	params.Key = req.Keyword
	params.DB = l.svcCtx.DB.Table(model.TableNameConversationGroup)

	list, i, err := comMysql.GetListCustom[model.ConversationGroup](&params, func(db *gorm.DB) {
		if req.UserId != 0 {
			db.Where("userId = ?", req.UserId)
		} else {
			db.Where("userId = ?", user.ID)
		}
		db.Order("updateTime desc")
	})
	if err != nil {
		return nil, err
	}
	resp.Total = int32(i)
	err = comCopier.CopyWithOption(&resp.List, list)
	if err != nil {
		return nil, err
	}
	return &resp, nil
}
